#include "stm32f10x.h"                  // Device header
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "ESP8266.h"
#include "ONENET.h"
#include "delay.h"
#include "OLED.h"
#include "timer.h"
#include "USART.h"
#include "Buzzer.h"
#include "Servo.h"
#include "GPIODO.h"
#include "dht11.h"
#include "Key.h"
#include "led.h"
#include "Motor.h"
#include "PWM.h"

#define BUFFER_SIZE 50 // 定义接收缓冲区大小为50
#define USE_WIFI 1   //使用WIFI的宏定义，debug的时候可以置0方便调试

char rxBuffer[BUFFER_SIZE]; // 接收缓冲区
char rxBuffer1[BUFFER_SIZE]; // 接收缓冲区

u8 rxIndex = 0; // 接收缓冲区索引
u8 rxIndex1 = 0;
char PUB_BUF[256]; // 上传数据缓冲区
const char *devSubTopic[] = {"led"}; // 要订阅的主题
const char devPubTopic[] = {"test"};
u8 *dataPtr = NULL;
u8 IRQ_flag = 0;
u8 Send_server_3s = 0;
u8 temp = 0,humi = 0;
u8 Open_flag = 0;
u8 keynum = 0;
u8 Open_time = 0;
u8 Set_Open_time = 10;
u8 leave_time = 0;
u8 Set_leave_time = 30;
u8 leave_flag = 0;
u8 Speed = 0;
u8 mode = 0;

unsigned char open = 0;

void IRQ_Task(void);
void init_progress(void);
void OLED_Show_fixed(void);
void OLED_Show_data(void);
void get_data(void);
void auto_control(void);

int main()
{
	init_progress();
	OLED_Show_fixed();
	
	while(1)
	{	
		get_data();
		
		if(mode == 0) {
			
			auto_control();
		}

		OLED_Show_data();
		IRQ_Task();
	}	
}
void get_data()
{
	leave_flag = Get_Up();
	keynum = Key_GetNum();
	if(keynum == 1)
	{
		if(Open_flag == 1)
			Open_flag = 0;
		else
			Open_flag = 1;
	}
	else if(keynum == 2)
	{
		if(mode == 1)mode = 0;
		else mode = 1;  
	}
	Motor_SetSpeed(Speed);
	if(Open_flag == 1) {
		Servo_SetAngle(90);
		GPIO_ResetBits(GPIOC, GPIO_Pin_13);
	}	
	else {
		Servo_SetAngle(0);
		GPIO_SetBits(GPIOC, GPIO_Pin_13);
	}
		
}
void auto_control()
{
	if(temp > 29)
	{

		Speed = 30;
		TIM_SetCompare1(TIM3, Speed);

	}
	else
	{

		Speed = 0;
		TIM_SetCompare1(TIM3, Speed);

	}
}


void TIM3_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM3,TIM_IT_Update) != RESET)//判断状态
	{ 
		TIM_ClearITPendingBit(TIM3,TIM_IT_Update);//清除中断待处理位
		if(Send_server_3s++ >= 2)
		{
			IRQ_flag = 1;
			Send_server_3s = 0;
		}
		if(Open_flag == 1)
			Open_time++;
		else
			Open_time = 0;
		if(Open_time >= 20)
		{
			if(Open_time % 20 == 0 && Open_time != 0)
			{
				Buzzer_ON();//蜂鸣器报警2秒红灯亮10秒
			}
			if(Open_time % 20 == 1)
			{
				Buzzer_OFF();//关闭蜂鸣器报警
			}
		}
		if(leave_flag == 1 && Open_flag == 1)
		{
			if (leave_time == 0) {
				Buzzer_ON();//蜂鸣器报警2秒红灯亮10秒
			}
			if (leave_time % 10 == 1) {
				Buzzer_OFF();//关闭蜂鸣器报警
			}
			leave_time++;//开始计时
		}
		else
			leave_time = 0;
		
		if(leave_time >= Set_leave_time)
		{
			Open_flag = 0;
			Buzzer_OFF();//关闭蜂鸣器报警
		}
		DHT11_Read_Data(&temp,&humi);
	}
}

void IRQ_Task()
{
	#if USE_WIFI
	if(IRQ_flag == 1) {
		char buf[100] = {0};
		memset(buf, 0, sizeof(buf));
		sprintf(buf, "AT+MQTTPUB=0,\"test\",\"{\\\"temp\\\":%u\\\"humi\\\":%u}\",0,0\r\n", temp, humi);
		while (ESP8266_SendCmd(buf, "OK"));
		IRQ_flag = 0;
	}
	char receive[100] = {0};
	u16 receive_flag = 1;
	memset(receive, 0, sizeof receive);
	receive_flag = ESP8266_GetIPD(50, receive);
	if (receive_flag == 0) {	
		if (strcmp(receive, "0,\"led\",1,1\r\n") == 0) {
			Speed = 30;
			PWM_SetCompare1(Speed);
		}
		if (strcmp(receive, "0,\"led\",1,0\r\n") == 0) {
			Speed = 0;
			PWM_SetCompare1(Speed);
		}
	}
	#endif
}
void init_progress()
{
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	delay_init(); // 延时函数初始化
	OLED_Init(); // OLED初始化
	Usart1_Init(115200); // 串口1初始化
	Usart2_Init(115200); // 串口2初始化
	Buzzer_Init();
	Buzzer_OFF();
	DHT11_Init();
	Servo_Init();
	GPIODO_Init();
	Key_Init();
	Motor_Init();
	LED_Init();
	#if	USE_WIFI
	OLED_ShowChinese(0,0,"正在初始化");
	OLED_Update();
	ESP8266_Init(); // ESP8266模块初始化
	#endif 
	Usart3_Init(115200);
	TIM3_Int_Init(10000 - 1, 7199); // 3s
	Buzzer_ON();
	delay_ms(100);
	Buzzer_OFF();
	OLED_ShowChinese(0,0,"初始化完成");
	OLED_Update();
	delay_ms(500);
	OLED_Clear();
	OLED_Update();
}
void OLED_Show_fixed()
{
	OLED_ShowChinese(0,0,"开门时间");
	OLED_ShowChinese(0,16,"温度");
	OLED_ShowChinese(0,32,"湿度");
	OLED_ShowChinese(0,48,"离开时间");
	OLED_ShowString(64,0,":",OLED_8X16);
	OLED_ShowString(32,16,":",OLED_8X16);
	OLED_ShowString(32,32,":",OLED_8X16);
	OLED_ShowString(64,48,":",OLED_8X16);
	OLED_Update();
}
void OLED_Show_data()
{
	OLED_ShowNum(72,0,Open_time,2,OLED_8X16);
	OLED_ShowNum(48,16,temp,2,OLED_8X16);
	OLED_ShowNum(48,32,humi,2,OLED_8X16);
	OLED_ShowNum(72,48,leave_time,2,OLED_8X16);
	if(Open_flag == 1)
		OLED_ShowChinese(100,16,"开");
	else
		OLED_ShowChinese(100,16,"关");
	if(mode == 0)
		OLED_ShowChinese(100,32,"自");
	else
		OLED_ShowChinese(100,32,"手");
	
	
	OLED_Update();
}
void USART3_IRQHandler(void)
{
    if (USART_GetITStatus(USART3, USART_IT_RXNE) != RESET)
    {
        // 读取接收到的数据
        char receivedChar = USART_ReceiveData(USART3);

        // 将接收到的字符存储到缓冲区
        if (receivedChar != '\r' && receivedChar != '\n')
            if (rxIndex < BUFFER_SIZE - 1)
            {
                rxBuffer[rxIndex++] = receivedChar;
                rxBuffer[rxIndex] = '\0'; // 在缓冲区末尾添加字符串终止符
            }

        // 如果接收到换行符，说明接收到了一个完整的字符串
        if (receivedChar == '\n')
        {
			if (strcmp(rxBuffer, "open") == 0) 
            {
				Open_flag = 1;//开冰箱门
            }
			if (strcmp(rxBuffer, "close") == 0) 
            {
				Open_flag = 0;//关冰箱门
            }
			if (strcmp(rxBuffer, "open_fans") == 0) 
            {
				if(mode == 1)
					open = 1;
            }
			if (strcmp(rxBuffer, "close_fans") == 0) 
            {
				if(mode == 1)
					open = 0;
            }
			if (strcmp(rxBuffer, "open_light") == 0) 
            {
				if(mode == 1)
					open = 1;
            }
			if (strcmp(rxBuffer, "close_light") == 0) 
            {
				if(mode == 1)
					open = 0;
            }
            // 重置缓冲区和索引
            rxIndex = 0;
            memset(rxBuffer, 0, sizeof(rxBuffer));
        }
    }
}
void USART1_IRQHandler(void)
{
    if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
    {
        // 读取接收到的数据
        char receivedChar1 = USART_ReceiveData(USART1);

        // 将接收到的字符存储到缓冲区
        if (receivedChar1 != '\r' && receivedChar1 != '\n')
            if (rxIndex1 < BUFFER_SIZE - 1)
            {
                rxBuffer1[rxIndex1++] = receivedChar1;
                rxBuffer1[rxIndex1] = '\0'; // 在缓冲区末尾添加字符串终止符
            }

        // 如果接收到换行符，说明接收到了一个完整的字符串
        if (receivedChar1 == '\n')
        {
			if (strcmp(rxBuffer1, "Door Unlocked") == 0) 
            {
				Open_flag = 1;//开冰箱门
				Usart_SendString(USART1, (unsigned char*)"Door Unlocked", strlen("Door Unlocked"));
            }

            // 重置缓冲区和索引
            rxIndex1 = 0;
            memset(rxBuffer1, 0, sizeof(rxBuffer1));
        }
    }

}
